package com.zhiyou.aifeng.smart_machine

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.baidu.mapapi.BDLocationHelper
import com.heweather.plugin.view.HeContent
import com.heweather.plugin.view.HeWeatherConfig
import com.jeremyliao.liveeventbus.utils.observe
import com.zhiyou.aifeng.common.base.gone
import com.zhiyou.aifeng.common.base.oneClick
import com.zhiyou.aifeng.common.helper.*
import com.zhiyou.aifeng.common_ui.base.BaseActivity
import com.zhiyou.aifeng.common_ui.base.BaseDialog
import com.zhiyou.aifeng.common_ui.base.addItems
import com.zhiyou.aifeng.common_ui.base.loadCircleImage
import com.zhiyou.aifeng.common_ui.model.BaseUrl
import com.zhiyou.aifeng.common_ui.model.CommonData
import com.zhiyou.aifeng.common_ui.oss.scaleImage
import com.zhiyou.aifeng.common_ui.router.Routers
import com.zhiyou.aifeng.common_ui.utils.*
import com.zhiyou.aifeng.viewmodel.MainViewModel
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.longToast
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONObject

@Route(path = Routers.main)
class MainActivity : BaseActivity() {

    private var isChecked = false
    private var mDialog: BaseDialog? = null
    private var mMatterList = ArrayList<CommonData>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setTransparentAndToolbar()
        initTitle()

        getServiceTel()
    }

    override fun getViewModel() = get<MainViewModel>()

    override fun onStart() {
        super.onStart()
        getData()
        getMatter()
        getMsgCount()
    }

    override fun initTitle(title: String, name: String, divider: Boolean) {
        main_apply.gone()
        initListeners()
        initWeather()

        main_bottom.bottomHide(55f)
        main_time.text = TimeHelper.getInstance().getNowTime("HH:mm")
        main_date.text = TimeHelper.getInstance().getNowTime("yyyy.M.d EEEE")
        getViewModel().startCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBy(
                onNext = {
                    main_time.text = TimeHelper.getInstance().getNowTime("HH:mm")
                    main_date.text = TimeHelper.getInstance().getNowTime("yyyy.M.d EEEE")
                }
            )

        observe("authState") {
            when (it) {
                "submit" -> mDialog?.dismiss()
            }
        }

        observe("orderPush") { getMatter() }
    }

    private fun initListeners() {
        main_message.oneClick { startActivity<MessageActivity>() }
        main_setting.oneClick { startActivity<SettingActivity>() }
        main_work.oneClick { startActivity<MatterActivity>() }
        main_wallet.oneClick { startActivity<WalletActivity>() }
        main_order.oneClick { startActivity<OrderActivity>() }
        main_machine.oneClick { startActivity<MachineActivity>() }
        main_repair.oneClick { startActivity<RepairActivity>() }
        main_rank.oneClick { startActivity<RankActivity>() }
        main_img.oneClick {
            if (getString("auth") == "2")
                startActivity<RealInfoActivity>()
        }
        main_apply.oneClick { startActivity<RealActivity>() }
        main_check.oneClick {
            if (mMatterList.isNotEmpty()) {
                startActivity<MatterDetailActivity>("orderId" to mMatterList[0].njsjid)
            }
        }
    }

    private fun checkAuth() {
        when (getString("auth")) {
            "0" -> showDialog()
            "3" -> {
                longToast("实名认证信息审核失败，请重新认证！")
                showDialog()
            }
        }

        if (!isChecked) {
            isChecked = true
            getViewModel().checkUpdate(this, true)
        }
    }

    private fun initWeather() {
        main_weather.apply {
            setDefaultBack(false)
            setStroke(0, Color.TRANSPARENT, 0, Color.TRANSPARENT)

            addTemp(leftTopLayout, 22, Color.WHITE)
            addWeatherIcon(rightLayout, 40)
            addCond(leftBottomLayout, 14, Color.WHITE)
            addWindIcon(leftBottomLayout, 14)
            addWind(leftBottomLayout, 14, Color.WHITE)
            setViewGravity(HeContent.GRAVITY_RIGHT)
            setViewPadding(10, 10, 10, 10)
            setOnClickListener(null)
        }
    }

    private fun showDialog() {
        if (mDialog?.isShowing == true) return
        mDialog = showRealDialog { startActivity<RealActivity>() }
    }

    @SuppressLint("SetTextI18n")
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().request(
            isLoading = false,
            requestUrl = BaseUrl.home,
            params = *arrayOf("uid" to getString("userId")),
            onResult = {
                val obj = JSONObject(it)
                main_num.text = obj.optNotEmpty("orderCnt", "0")
                main_num1.text = obj.optNotEmpty("vehicleCnt", "0")
                main_percent.text = "${obj.optNotNull("commentRate").formatDecimalWhenHave()}%"

                val user = obj.optJSONObject("user") ?: JSONObject()
                putShared("userName", user.optNotNull("nickname"))
                putShared("userHead", user.optNotNull("avatar"))
                putShared("realName", user.optNotNull("realname"))
                putShared("balance", user.optNotNull("userBalance").formatDecimal())
                putShared("auth", user.optNotNull("realAuthStatus"))

                putShared("idCard", user.optNotNull("number"))
                putShared("authRegion", user.optNotNull("regionAddr"))
                putShared("authAdress", user.optNotNull("address"))
                putShared("authGroup", user.optNotNull("imgGroup"))
                putShared("authFront", user.optNotNull("imgFront"))
                putShared("authBack", user.optNotNull("imgBack"))

                main_balance.text =
                    getString("balance")
                        .formatDecimalWhenHave(
                            default = "0.00",
                            zeroValue = "0.00"
                        )

                main_name.text = when {
                    getString("realName").isNotEmpty() -> getString("realName")
                    getString("userName").isNotEmpty() -> getString("userName")
                    else -> getString("phone")
                }

                if (main_img.getTag(R.id.empty_img) == null
                    || main_img.getTag(R.id.empty_img) != getString("userHead")
                ) {
                    main_img.loadCircleImage(getString("userHead").scaleImage())
                    main_img.setTag(R.id.empty_img, getString("userHead"))
                }

                checkAuth()
                main_author.text = when (getString("auth")) {
                    "1" -> "认证中"
                    "2" -> "认证机手"
                    else -> "未认证"
                }

                val address = user.optNotNull("regionAddr")
                if (address.isNotEmpty()) main_adress.text = address.split(" ")[2]

                BDLocationHelper.getInstance(this)
                    .startLocation(100) { location, success, codes ->
                        if (success && 100 in codes) {
                            if (address.isEmpty()) main_adress.text = location.district

                            HeWeatherConfig.init(
                                getViewModel().getKey(),
                                "${location.district},${location.city}"
                            )
                            main_weather.show()
                            main_weather.oneClick {
                                startActivity<WeatherActivity>(
                                    "city" to location.city,
                                    "district" to location.district
                                )
                            }
                        }
                    }
            }
        )
    }

    private fun getServiceTel() {
        getViewModel().getHotline()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    if (!it.isNullOrEmpty()) {
                        putShared("serviceTel", it[0].name)
                    }
                }
            )
    }

    @SuppressLint("SetTextI18n")
    private fun getMatter() {
        getViewModel().getMatterList(getString("userId"))
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mMatterList.clear()
                    mMatterList.addItems(it)

                    if (mMatterList.isNotEmpty()) {
                        val item = mMatterList[0]
                        main_msg.text =
                            "${item.work_type_name} 亩数：${
                            item.area.formatDecimal()}亩 价格：${
                            item.price.formatDecimal()}元/亩 时间：${
                            item.preset_date.getTimeString("yyyy-MM-dd HH:mm")}（预计） 地址：${
                            item.region_addr.replace(" ", "") + item.address}"
                        main_bottom.bottomShow()
                    } else main_bottom.bottomHide(55f)
                }
            )
    }

    private fun getMsgCount() {
        getViewModel().request(
            isLoading = false,
            requestUrl = BaseUrl.msgUnread,
            params = *arrayOf(
                "uid" to getString("userId"),
                "type" to 2
            ),
            onResult = {
                main_count.visibility = if (it.toNotInt() > 0) View.VISIBLE else View.GONE
            }
        )
    }

    private var exitTime: Long = 0
    override fun onBackPressed() {
        if (System.currentTimeMillis() - exitTime > 2000) {
            toast("再按一次退出程序")
            exitTime = System.currentTimeMillis()
        } else super.onBackPressed()
    }

    override fun onDestroy() {
        super.onDestroy()
        BDLocationHelper.getInstance(this).apply {
            stopLocation()
            removeCode(100)
        }
    }

}